package com.zhou.server.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class OnlineUserService {
    private static final String ONLINE_USERS_KEY = "chat:online_users";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 用户上线
    public void userLogin(String userId) {
        redisTemplate.opsForSet().add(ONLINE_USERS_KEY, userId);
        redisTemplate.expire(ONLINE_USERS_KEY, 1, TimeUnit.DAYS);
    }

    // 用户下线
    public void userLogout(String name) {
        redisTemplate.opsForSet().remove(ONLINE_USERS_KEY, name);
    }

    // 获取在线用户列表
    public Set<String> getOnlineUsers() {
        return redisTemplate.opsForSet().members(ONLINE_USERS_KEY);
    }
}